

export interface ActionType {
	type: string
	payload: any
}

export interface StateType {
	car: any[]
}


const initState: StateType = {
	car: []
}

const reducer = (state = initState, action: ActionType) => {

	switch (action.type) {
		case 'addCar':
			// 仓库是否存在该商品
			const currItem = state.car.find((v) => v.id === action.payload.id)
			// 存在直接++
			if (currItem) {
				currItem.count++
				return {
					...state,
					car: [...state.car]
				}
			} else {
				// 不存在  商品个数初始值1
				action.payload.count = 1

				// 不存在  添加商品的选中状态 
				action.payload.isChecked = false

				return {
					...state,
					car: [...state.car, action.payload]
				}
			}
		case 'subCar':
			{
				// 找到该商品
				const currItem = state.car.find((v) => v.id === action.payload.id)
				if (currItem) {
					if (currItem.count <= 1) {
						state.car = state.car.filter(v => v.id !== action.payload.id)
					} else {
						currItem.count--
					}
					return {
						...state,
						car: [...state.car]
					}
				}
				return state
			}
		// 单选
		case 'switchCheck':
			{
				// 找到数据
				const currItem = state.car.find(v => v.id === action.payload.id)
				// 切换状态
				currItem.isChecked = !currItem.isChecked

				return {
					...state,
					car: [...state.car]
				}
			}
		// 全选
		case 'switchCheckAll':
			// 修改所有单选的状态和全选状态一致
			state.car.forEach(v => v.isChecked = action.payload)
			return {
				...state,
				car: [...state.car]
			}
		default:
			return state
	}
}


export default reducer